初始化完全专用模板时,C++ 类型别名不明确

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

我试图使用类型别名作为模板参数来初始化我的模板类,但只创建了我的类的专用版本。我知道问题在于我的别名不明确。有解决办法吗?

#include <iostream>

using Type1 = size_t;
using Type2 = size_t;

template <class Type>
class SomeClass {
public:
    void doSomething() {
    }
};

template <>
class SomeClass<Type1> {
public:
};

int main() {
    SomeClass<Type1> someClass1;    // SomeClass<Type1> is initialized

    SomeClass<Type2> someClass2;    // ... and also SomeClass<Type1> is initialized ???
    someClass2.doSomething();       // and therefor doSomething() is not working...
}
c++ alias using template-specialization ambiguous
1个回答
1
投票

你所要求的是不可能的。不直接。类型别名仅引入引用该类型的名称。在您的代码中

Type1
Type2
确实是同一类型。

你能做什么:一定程度的间接。

#include <iostream>


template <class Type>
class SomeClass {
public:
    void doSomething() {
    }
};


struct Type1 {
    using type = size_t;    
};
struct Type2 {
    using type = size_t;
};

template <>
class SomeClass<Type1> {
public:
};


int main() {
    SomeClass<Type1> someClass1;    

    SomeClass<Type2> someClass2;    
    someClass2.doSomething();       
}

之前在

Type
中使用
SomeClass
现在使用
typename Type::type
。现在
SomeClass<Type1>
SomeClass<Type2>
是两个不同的实例化,但是它们可以使用相同的
type

© www.soinside.com 2019 - 2024. All rights reserved.