1
void func1(int){} void func2(char){} template <typename T> void (*p)(T); // error p = func1; p = func2; 

Why cant we define a pointer like p?

0

4 Answers 4

4

You can do it like this:

template<class T> using p = void (*)(T); void f(int ); p<int> x = &f; 
Sign up to request clarification or add additional context in comments.

3 Comments

Downvote? Can the honorable downvoter please explain what is the problem with my answer?
Probably the OP because he was wanting to write p = func1; without any template args.
@kfsone, that would not be possible anyways.
3

C++14 actually allows variable templates, so your definition of the template p is valid.

However, p is a variable template, not a variable; in order to get an actual variable, you need to instantiate it with a particular type, like so:

p<int> = func1; p<char> = func2; 

8 Comments

In OP's example, p is a type, not a variable.
@SergeyA I beg to differ. If you compile with C++14, p is a variable template.
@SergeyA OP seems to be trying to make a variable which will accept a pointer to either a void (*)(int) or a void (*)(void).
@kfsone, may be... OP was notably vague in their intention.
@Brian, I think, I am not clear as to what OP actually wants to do. You might be correct in your understanding of OP's goals.
|
0

In your example, the variable p is able to be assigned objects of unrelated types (here, two incompatible function pointers). Such a dynamic change in apparent type is not supported by templates, which are strictly static (compile-time) constructs.

If you want to achieve such a type-shifting object, type erasure techniques must be applied. In that specific case, std::function looks like it could be of use to you, but you still need to decide on a fixed function signature (how would you call it otherwise ?).

Comments

0

Thanks to @SergeyA and @Brian 's help, I solved the problem and I edit my answer here.

template<typename T> void (*p)(T): in this case, p is a variable template(c++14). So we can use p like this:

p<int> = func1; p<char> = func2; 

template<class T> using p = void (*)(T): in this case, p is a kind of type(it's just like typedef but we cant use typedef for alias template). Meaning that we should use it like this:

p<int> x1 = func1; p<char> x2 = func2; 

Btw, both of them are template declaration, so we can't put them at any block scope.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.