如何使用默认类型T创建类型T和类型T模板的值?

问题描述 投票:0回答:1

正如问题所说。我想创建一个模板,例如类的,它接受 typename T 和 T val 作为参数,其中我可以指定默认的 T 类型 我试过这个:

template <typename T = int, T V = 0>
class Example
{

};

   

Example<int, 1> a; // compiles
Example<int> a; // compiles
Example a; // compiles
Example<1> a; // Error: "expected type specifier"

但我想做的一件事却没有。 我怎样才能正确地做到这一点?

c++ templates
1个回答
1
投票

不可能支持这种精确的语法(同时支持所有 4 种形式)。

我能想到的最接近的是:

template <auto V = 0>
struct Example {};
Example<int(1)> a; // Type and value.
Example<int{}> a;  // Type only.
Example a;         // Neither.
Example<1> a;      // Value only.
© www.soinside.com 2019 - 2024. All rights reserved.