在编译期间,clang中的代码我有警告(在vc中它工作正常):
warning : explicit specialization of ‘Helper’ within class scope is a
Microsoft extension [-Wmicrosoft]
#include <stdio.h>
#include <string>
enum class Car { BMW };
class C
{
static void Method() { puts("inner");}
};
template<typename T>
class BaseClass
{
private:
template<typename V>
struct Helper;
template<>
struct Helper<Car>
{
typedef C InnerType;
static const char* Name() { return "Car"; }
};
typedef Helper<T> Info;
typedef typename Info::InnerType InnerType;
private:
T v;
protected:
BaseClass()
{ }
public:
T Value() const { return v; }
std::string Name() const { return Info::Name(); }
static void Print() { InnerType::Method(); }
};
class MyCar : public BaseClass<Car>
{
public:
MyCar() : BaseClass() {}
};
int main()
{
MyCar a;
printf("%s\n", a.Name().c_str());
// a.Print();
}
我试图在BaseClass之外移动Helper类的特化以与标准兼容:
template<> template<>
struct BaseClass<Car>::Helper<Car>
{
typedef C InnerType;
static const char* Name() { return "Car"; }
};
但是现在我有编译错误:
error: implicit instantiation of undefined template ‘BaseClass::Helper’
如果我删除该行:typedef typename Info :: InnerType InnerType; (以及功能Print中的相关用法)然后一切正常.
是否可以修复此错误?我想把我的助手课程保密.
最佳答案 你可以这样做:
#include <stdio.h>
#include <string>
enum class Car { BMW };
class C
{
static void Method() { puts("inner");}
};
template<typename T>
class BaseClass
{
private:
template<typename V>
struct Helper;
template<typename V>
using Info = Helper<V>;
template<typename V>
using InnerType = typename Info<V>::InnerType;
private:
T v;
protected:
BaseClass()
{ }
public:
T Value() const { return v; }
std::string Name() const { return Info<T>::Name(); }
static void Print() { InnerType<T>::Method(); }
};
template<> template<>
struct BaseClass<Car>::Helper<Car>
{
typedef C InnerType;
static const char* Name() { return "Car"; }
};
class MyCar : public BaseClass<Car>
{
public:
MyCar() : BaseClass() {}
};
int main()
{
MyCar a;
printf("%s\n", a.Name().c_str());
//a.Print();
}
(gcc 5.1 / clang 3.6,-std = C 11)
该程序打印“汽车”.