是否可以将类模板用作模板专业化中的参数?
我希望能够使用类似的代码foo<Foo<int>>()
(请参见#3
源代码),并具有用于该模板实例运行的唯一代码。目前,只有普通的专业化工作(请参阅参考资料#2
)。
之前的类似问题使我相信该方法#3
可行,但至少在msvc2012下该代码无效。
我想做的事可能吗?如果是这样,怎么办?
来源
// Test struct.
template<class T>
struct Foo
{
T foo;
};
// #1 Ordinary template
template<class T>
T foo()
{
return T();
}
// #2 Template specialization
template<>
int foo<int>()
{
return 42;
}
// #3 Template specialization with template as parameter? Not working.
template<>
template<typename T>
Foo<T> foo<Foo<T>>()
{
return Foo<T>();
}
我重写了Marco A.的解决方案,以允许我保留原始语法。
然后,我还提出了第二种解决方案,该解决方案使用“输出参数”而不是“返回值”。我认为此解决方案更好,因为维护和完成相同工作更简单。
解决方案1(用原始语法重写了Marco A的解决方案)
#include <iostream>
using namespace std;
// Test struct
template<class T>
struct Foo
{
T foo;
};
// #1 Ordinary template
template<class T>
struct FooWrapper
{
static T foo()
{
return T();
}
};
// #2 Template specialization
template<>
struct FooWrapper<int>
{
static int foo()
{
return 42;
}
};
// #3 Template specialization with template as parameter
template<class T>
struct FooWrapper<Foo<T>>
{
static Foo<T> foo()
{
return Foo<T>();
}
};
// Hides wrapper implementation
template<class T>
T foo()
{
return FooWrapper<T>::foo();
}
int main()
{
cout << foo<bool>() << endl;
cout << foo<int>() << endl;
cout << foo<Foo<int>>().foo << endl;
return 0;
}
解决方案2(使用out参数更简单,可能更好的解决方案)
#include <iostream>
using namespace std;
// Test struct
template<class T>
struct Foo
{
T foo;
int bar;
};
// #1 General case
template<class T>
void foo(T& value)
{
value = T();
}
// #2 Special case
void foo(int& value)
{
value = 2;
}
// #3 Special case with class template
template<class T>
void foo(Foo<T>& value)
{
value.bar = 3;
}
// Function templates with hidden specializations
template<class T>
T foo()
{
T value;
foo(value);
return value;
}
int main()
{
cout << foo<bool>() << endl;
cout << foo<int>() << endl;
cout << foo<Foo<int>>().bar << endl;
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句