这是一个带有默认模板参数的模板类:
#include <cstdio>
constexpr int d = 1;
template <int a = d> struct test;
template <> struct test<1> {
test(int a) { printf("%d\n", a); }
};
template <> struct test<2> {
test() { printf("%d\n", 2); }
};
int main() { test t{1}; }
奇怪的是,如果
d=1
它不会编译,而d=2
则没问题。如果我想在d=1
时使用它,我必须这样做:test<> t{1};
。这不是有点违反直觉吗?
抱歉造成误解,如果
d=2
,你必须这样编译:
int main() {test t;} /// since test<2> has no argument for constructor
海湾合作委员会版本:11.2 没有特殊的编译命令
您的设置不提供任何模板参数推导源。仅当您提供模板参数列表(但您没有提供)时,才会尝试为非类型参数设置默认值。 如果您不喜欢空 V 形,例如对于其他模板中的一般使用,有一个解决方法,使用别名:
constexpr int d = 1;
template <int a> struct test_impl;
template <> struct test_impl<1> {
test_impl(int a) { printf("%d\n", a); }
};
template <> struct test_impl<2> {
test_impl() { printf("%d\n", 2); }
};
using test = test_impl<d>;
int main() { test t{1}; }