英文:
C++ specialization of template with templated type
问题
无法编译的理想但不工作的实现:
template<class D> class Dummy{public: D val;};
template<typename T> T foo();
template<> int foo<int>()
{
return 0;
}
template<typename D> Dummy<D> foo<Dummy<D>>()
{
return Dummy<D>{};
}
我得到错误信息:不允许非类、非变量的部分特化 'foo<Dummy<D>>'
。
英文:
I’d like to do a generic function which will be specialized with some types, but I also would like to specialized with templated types, which is not allowed by the compiler.
Is there a way to get around this ?
Ideal not working implementation:
template<class D> class Dummy{public: D val;};
template<typename T> T foo();
template<> int foo<int>()
{
return 0;
}
template<typename D> Dummy<D> foo<Dummy<D>>()
{
return Dummy<D>{};
}
I get the error non-class, non-variable partial specialization ‘foo<Dummy<D> >’ is not allowed
答案1
得分: 1
如果有人有问题X,解决方案是Y,那么99%的时间专门化函数模板是Z。
使函数委托给实际可以以任何方式专门化的内容:
template<typename T>
struct FooImpl {
static void func() = delete; // 删除的默认实现
// 需要专门化才能有效
// 不严格要求,但提供更多信息的错误
};
template<>
struct FooImpl<int> {
static int func() { return 1; }
};
template<typename T>
struct FooImpl<Dummy<T>> {
static Dummy<T> func() { return {}; }
};
template<typename T>
T foo() {
return FooImpl<T>::func();
}
英文:
> Is there a way to get around this?
If a someone has a problem X, and the solution is Y, then 99% of the time specializing function templates is Z.
Make the function delegate to something that actually can be specialized any way you want:
template<typename T>
struct FooImpl {
static void func() = delete; // Deleted default implementation
// Need to specialize to be valid
// Not strictly required, but gives
// more informative errors
};
template<>
struct FooImpl<int> {
static int func() { return 1; }
};
template<typename T>
struct FooImpl<Dummy<T>> {
static Dummy<T> func() { return {}; }
};
template<typename T>
T foo() {
return FooImpl<T>::func();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论