c++ - C++ 中的模板和预处理

标签 c++ templates if-statement enums c++03

如何编译这段代码:

#include <iostream>
using namespace std;

enum E { A, B};

template< E x>
class C {
public:
    #if( x == A)
        static void foo() {
            cout << "A";
        }
    #elif( x == B)
        static void goo() {
            cout << "B";
        }
    #endif
};


int main() {
    C< A>::foo();
    C< B>::goo();

    return 0;
}

error: ‘goo’ is not a member of ‘C<(E)1u>’

我有两个大类,只有几行不同,所以我想制作枚举模板。问题是这一行有 using关键字,所以我不知道该放什么。

有什么正确的方法吗?

PS> 我必须使用 C++03。

编辑:一点澄清。我知道 template<>构造,但我不想使用它,因为这样我得到了很多代码重复。也许我可以以某种方式进行部分“模板实例化”(如果这是 template<> 的正确术语)?

假设我有两个类(我不会有更多):

class A {
public:
//…a lot of code…
//few lines that differs in A and B
}

class B {
//…the same mass of code…
//few lines that differs in A and B
}

所以我决定在 enum 上制作模板:

enum E { A, B}
template< E>
class C{
//…common code…
}

现在我不知道如何处理这 A 和 B 不同的几行。我知道常见的方法是进行模板实例化,但是我会得到我对类 A 的确切了解。和 B .

从 OOP 的角度来看,我应该使用 common Base对于 AB .但问题是 AB已经一样了。它们仅在行上有所不同:

using CanStoreKeyValue< QString, Request>::set;
using CanStoreKeyValue< QString, Response>::set;

哪里ResponseRequest是类型定义。此外,在我的代码中 AB是同一个模板化抽象类的 child 。当然,他们用不同的模板参数继承了它。这不知何故打破了模板枚举的使用——编译器只是看不到一些虚拟方法不再是纯粹的。所以……这就是为什么我在问我在问什么。我认为预处理器可以通过 #if 与模板引擎交互-指令(最后,它们都是编译时进程)。

最佳答案

您不能使用预处理器来实现您想要做的事情。您需要的是模板特化:

enum E { A, B};

template< E x>
class C;

template <>
class C<A> {
public:
    static void foo() {
        cout << "A";
    }
};

template <>
class C<B> {
public:
    static void goo() {
        cout << "B";
    }
};

您更新后的问题仍然可以通过模板特化来解决:

enum E { A, B };

template< E x >
struct CanStoreKeyValueHelper;

template<>
struct CanStoreKeyValueHelper<A> {
    typedef CanStoreKeyValue< QString, Request>::set type;
};

template<>
struct CanStoreKeyValueHelper<B> {
    typedef CanStoreKeyValue< QString, Response>::set type;
};

template< E x>
class SuperPuperBigClass {
public:
    typedef typename CanStoreKeyValueHelper<x>::type set;
    ...
};

但不清楚为什么你不把它简单化为:

template<class T>
class SuperPuperBigClass {
public:
    typedef typename CanStoreKeyValue<QString, T>::set set;
};

并使用 Request 和 Response 类型实例化它

关于c++ - C++ 中的模板和预处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24916346/

相关文章:

C++模板结果类型

python if语句太长太难看,有没有办法缩短它

r - 如何检查字符串中是否存在元音?并返回1或0?

c++ - 将类函数与其实际功能分开声明有什么好处?

C++ Stringstream int 到 string 但返回 null

c++ - 右值和左值引用的模板特化

c++ - 指定模板参数

c++ - 在 C++ 中查找 char* 数组中的 char* 元素

c++ - operator= 在我的自定义字符串类中不能正常工作

java - 简化java中复杂的if语句