簡體   English   中英

在同一個類中具有不同類型名稱的同一模板的多個特化

[英]Multiple specializations of the same template with different typenames in a single class

我正在實現一個觀察者模式作為模板,並希望一個類附加不同的偵聽器類型。 問題是,使用不同類型多次在單個類中使用相同的模板似乎是不可能的。 據我所知,它應該是可能的,因為方法名稱無論如何都會有不同的類型,所以它們應該被修改成不同的名稱。 但是我得到的錯誤不是在鏈接時,而是在編譯時,所以我想知道我做錯了什么或者根本不可能。

為了證明這個問題我寫了一個SSCE:

#include <iostream>
#include <string>

template<typename T>
class Comparator
{
public:
    Comparator(void) { mCounter = 0; };
    virtual ~Comparator(void) {};

    bool equals(T oFirst, T oSecond)
    {
        mCounter++;
        if(oFirst != oSecond)
            return false;

        return true;
    }

    int getCounter(void)
    {
        return mCounter;
    }

private:
    int mCounter;
};

class TestClass :
    public Comparator<int>,
    public Comparator<void *>
{
public:
    TestClass(void) {};
    virtual ~TestClass(void) {};
};

int main(int argc, char *argv[])
{
    TestClass t1;
    TestClass *t2 = &t1;
    TestClass *t3 = new TestClass();
    int v1 = 1;
    int v2 = 2;
    bool b = t1.equals(v1, v2);
    std::cout << b << std::endl;
    std::cout << t1.equals(&t1, &t2) << std::endl;
    std::cout << t1.getCounter() << std::endl;

    delete t3;

    return 0;
}

當我使用gcc(使用Cx11選項)編譯它時,我收到以下錯誤:

||=== Build: Debug in CPPMingW (compiler: GNU GCC Compiler) ===|
D:\src\c\Tests\CPPMingW\main.cpp||In function 'int main(int, char**)':|
D:\src\c\Tests\CPPMingW\main.cpp|38|error: request for member 'equals' is ambiguous|
D:\src\c\Tests\CPPMingW\main.cpp|12|note: candidates are: bool Comparator<T>::equals(T, T) [with T = void*]|
D:\src\c\Tests\CPPMingW\main.cpp|12|note:                 bool Comparator<T>::equals(T, T) [with T = int]|
D:\src\c\Tests\CPPMingW\main.cpp|38|error: expected primary-expression before 'int'|
D:\src\c\Tests\CPPMingW\main.cpp|38|error: expected ';' before 'int'|
D:\src\c\Tests\CPPMingW\main.cpp|39|error: request for member 'equals' is ambiguous|
D:\src\c\Tests\CPPMingW\main.cpp|12|note: candidates are: bool Comparator<T>::equals(T, T) [with T = void*]|
D:\src\c\Tests\CPPMingW\main.cpp|12|note:                 bool Comparator<T>::equals(T, T) [with T = int]|
D:\src\c\Tests\CPPMingW\main.cpp|35|warning: unused variable 'v1' [-Wunused-variable]|
D:\src\c\Tests\CPPMingW\main.cpp|36|warning: unused variable 'v2' [-Wunused-variable]|
||=== Build failed: 4 error(s), 2 warning(s) (0 minute(s), 1 second(s)) ===|

在這個例子中,我真的不明白為什么它應該是ambigous,因為在兩個調用中數據類型都是明確定義的,並且與其他模板特化完全不同。 我期望來自getCounter()的errof,因為這實際上是不可確定的。

你希望你的基類中的equals參與重載解析,好像它們都是在派生類中定義的,但不幸的是它不能那樣工作(我不知道為什么不這樣)。

您可以顯式調用您想要的equals版本:

t1.Comparator<int>::equals(v1, v2);

或者您可以在派生類(公共部分)中添加它:

using Comparator<int>::equals;
using Comparator<void*>::equals;

這應該允許基類的2等於函數執行標准的重載決策。 您也可以通過在派生類中編寫 2 equals函數並讓每個函數調用相應的基類equals來實現相同的功能。

需要注意的是: Comparator<int>Comparator<void*>是完全獨立的類。 他們彼此都不知道。 如果它們不是模板但也有不同的名稱,則表現相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM