为什么具有默认模板参数的模板类的专用构造函数不能有参数?

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

这是一个带有默认模板参数的模板类:

#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 没有特殊的编译命令

c++ templates specialization
1个回答
0
投票

您的设置不提供任何模板参数推导源。仅当您提供模板参数列表(但您没有提供)时,才会尝试为非类型参数设置默认值。 如果您不喜欢空 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}; }
© www.soinside.com 2019 - 2024. All rights reserved.