我對通用結構的成員函式的特化有問題。
我的目標是用各種 std::vector 專門化 Bar 的成員函式 Run。
#include <iostream>
#include <vector>
// (1) compile
template <typename T>
struct Foo {
T Run() {
std::cout << "Foo not specialized" << std::endl;
return T();
};
};
// (2) compile
template <typename T>
struct Foo<std::vector<T>> {
std::vector<T> Run() {
std::cout << "Foo specialized" << std::endl;
return std::vector<T>();
};
};
template <typename T> struct Bar
{
T Run();
};
// (3) compiles
template<typename T>
T Bar<T>::Run() {
std::cout << "Bar not specialized" << std::endl;
return T();
};
// (3) compiles
template<>
std::vector<bool> Bar<std::vector<bool>>::Run() {
std::cout << "Bar specialized" << std::endl;
return std::vector<bool>();
};
// (4) wont compile: error: invalid use of incomplete type 'struct Bar<std::vector<T> >
template<typename T>
std::vector<T> Bar<std::vector<T>>::Run() {
std::cout << "Bar specialized" << std::endl;
return std::vector<T>();
};
int main(int argc, char const *argv[]) {
Foo<bool> f1;
bool rf1 = f1.Run();
Foo<std::vector<int>> f2;
std::vector<int> rf2 = f2.Run();
Bar<bool> b1;
bool rb1 = b1.Run();
Bar<std::vector<bool>> b2;
std::vector<bool> rb2 = b2.Run();
Bar<std::vector<int>> b3;
std::vector<int> rb3 = b3.Run();
return 0;
};
如果我將其注釋掉,它可能無法編譯,請參閱 (4)。有沒有辦法讓這個作業。先感謝您。
演示未編譯
演示編譯
uj5u.com熱心網友回復:
模板函式不能是部分專門化的。
你可以用蹦床和超載來做到這一點。就像Run(){ DoRun(*this)然后寫DoRun多載一樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/371195.html
