Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

c++ - When a compiler can infer a template parameter?

Sometimes it works sometimes not:

template <class T> 
void f(T t) {}

template <class T>
class MyClass {
public:
  MyClass(T t) {}
};

void test () {
  f<int>(5);
  MyClass<int> mc(5);
  f(5);
  MyClass mc(5); // this doesn't work
}

Is there a way to hack around the example above? I.e. force the compiler to infer the template parameter from constructor parameter.

Will this be fixed in the future, or is there a good reason not to?

What is the general rule when compiler can infer template parameter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Template parameters can be inferred for function templates when the parameter type can be deduced from the template parameters

So it can be inferred here:

template <typename T>
void f(T t);

template <typename T>
void f(std::vector<T> v);

but not here:

template <typename T>
T f() {
  return T();
}

And not in class templates.

So the usual solution to your problem is to create a wrapper function, similar to the standard library function std::make_pair:

  template <class T>
    class MyClass {
    public:
        MyClass(T t) {}
        void print(){
            std::cout<<"try MyClass"<<std::endl;
        }
    };

    template <typename T>
    MyClass<T> MakeMyClass(T t) { return MyClass<T>(t); }

and then call auto a = MakeMyClass(5); to instantiate the class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...