2

コンパイラは、コンパイル時に派生クラスへのポインターを取得できず、それが基底クラスを持っていることを認識できませんか? 次のテストに基づいて、できないようです。問題が発生する場所については、最後に私のコメントを参照してください。

どうすればこれを機能させることができますか?

std::string nonSpecStr = "non specialized func";
std::string const specStr = "specialized func";
std::string const nonTemplateStr = "non template func";

class Base {};
class Derived : public Base {};
class OtherClass {};


template <typename T> std::string func(T * i_obj)
{ return nonSpecStr; }

template <> std::string func<Base>(Base * i_obj)
{ return specStr; }

std::string func(Base * i_obj)
{ return nonTemplateStr; }

class TemplateFunctionResolutionTest
{
public:
    void run()
    {
        // Function resolution order
        // 1. non-template functions
        // 2. specialized template functions
        // 3. template functions
        Base * base = new Base;
        assert(nonTemplateStr == func(base));

        Base * derived = new Derived;
        assert(nonTemplateStr == func(derived));

        OtherClass * otherClass = new OtherClass;
        assert(nonSpecStr == func(otherClass));


        // Why doesn't this resolve to the non-template function?
        Derived * derivedD = new Derived;
        assert(nonSpecStr == func(derivedD));
    }
};
4

1 に答える 1

4
Derived * derivedD = new Derived;
assert(nonSpecStr == func(derivedD));

これは、期待どおりに非テンプレート関数に解決されません。これを行うには、からDerived *へのキャストをBase *実行する必要があるためです。ただし、このキャストはテンプレート バージョンには必要ないため、オーバーロードの解決時にテンプレート バージョンの方が一致します。

テンプレート関数が両方Baseに一致しないように強制Derivedするには、SFINAE を使用してこれらのタイプの両方を拒否できます。

#include <string>
#include <iostream>
#include <type_traits>
#include <memory>

class Base {};
class Derived : public Base {};
class OtherClass {};

template <typename T> 
typename std::enable_if<
    !std::is_base_of<Base,T>::value,std::string
  >::type
  func(T *)
{ return "template function"; }

std::string func(Base *)
{ return "non template function"; }

int main()
{
  std::unique_ptr<Base> p1( new Base );
  std::cout << func(p1.get()) << std::endl;

  std::unique_ptr<Derived> p2( new Derived );
  std::cout << func(p2.get()) << std::endl;

  std::unique_ptr<Base> p3( new Derived );
  std::cout << func(p3.get()) << std::endl;

  std::unique_ptr<OtherClass> p4( new OtherClass );
  std::cout << func(p4.get()) << std::endl;
}

出力:

non template function
non template function
non template function
template function
于 2012-08-10T23:46:29.867 に答える