我有以下模板类和示例类:
template<typename A, typename B, typename C = typename A::Nested<B>>
struct X
{
X()
{
std::cout << "A is : " << A::who() << std::endl;
std::cout << "B is : " << B::who() << std::endl;
std::cout << "C is : " << C::who() << std::endl;
}
};
struct Bsample
{
static const char* who() { return "Bsample"; }
};
struct Asample
{
template<typename B>
struct Nested;
template<>
struct Nested<Bsample>
{
static const char* who() { return "Asample::Nested<Bsample>"; }
};
static const char* who() { return "Asample"; }
};
当使用 vc14 时,上面的代码编译得很好,并为 X<Asample, Bsample>
的实例化生成预期的行为。默认模板参数C
至Asample::Nested<Bsample>
.
但是,当使用 GCC 5.1 编译时,出现以下错误:
prog.cpp:4:65: error: expected '>' before '<' token
template<typename A, typename B, typename C = typename A::Nested<B>>
^
我尝试了几种组合来声明模板参数 C
的默认值,使用template
, typename
,...但是用 GCC 编译这段代码没有成功。
如何使这段代码符合C++标准并用GCC编译?
感谢帮助
编辑:添加到 TartanLlama 接受的答案
除了 TartanLlama 接受的答案之外,我还必须在结束模板参数小括号之间插入一个空格(空格):
template<typename A, typename B, typename C = typename A::Nested<B> >
// blank (space) added here ^
否则,GCC 会发出以下错误(当未指定选项 -std=c++11
时):
error: spurious '>>', use '>' to terminate a template argument list
template<typename A, typename B, typename C = typename A::template Nested<B>>
^
最佳答案
您需要typename
和 template
这里:
template<typename A, typename B, typename C = typename A::template Nested<B>>
template
说比 A::Nested
是一个模板,typename
说A::Nested<B>
命名一个类型。
您还需要移动 Asample::Nested
的特化出Asample
定义:
struct Asample
{
template<typename B>
struct Nested;
static const char* who() { return "Asample"; }
};
template<>
struct Asample::Nested<Bsample>
{
static const char* who() { return "Asample::Nested<Bsample>"; }
};
关于c++ - 如何根据其他参数设置嵌套模板类实例化作为默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40503145/