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
300 views
in Technique[技术] by (71.8m points)

c++ - Force function to be called only with specific types

I was looking at enforcing type safety when casting char* to bool in C++11 and it was suggested that if you do

template<typename T>
void foo(T) = delete;

void foo(int f) {}

That foo will only work when given a explicit int argument. I made a test case:

template<typename T>
void foo(T) = delete;

void foo(int f) {}

int main()
{
    foo(1);
    foo(3.0);
    foo(short(5));
    foo(float(7.0));
    foo(long(9));
}

I used coliru to compile the code with g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out(live example) and I got the following errors:

main.cpp: In function 'int main()':
main.cpp:9:12: error: use of deleted function 'void foo(T) [with T = double]'
     foo(3.0);
            ^
main.cpp:2:6: note: declared here
 void foo(T) = delete;
      ^
main.cpp:10:17: error: use of deleted function 'void foo(T) [with T = short int]'
     foo(short(5));
                 ^
main.cpp:2:6: note: declared here
 void foo(T) = delete;
      ^
main.cpp:11:19: error: use of deleted function 'void foo(T) [with T = float]'
     foo(float(7.0));
                   ^
main.cpp:2:6: note: declared here
 void foo(T) = delete;
      ^
main.cpp:12:16: error: use of deleted function 'void foo(T) [with T = long int]'
     foo(long(9));
                ^
main.cpp:2:6: note: declared here
 void foo(T) = delete;
      ^

compiling with clang also produced similar errors

Now when I was reading about = delete on cppreference it stated

If the function is overloaded, overload resolution takes place first, and the program is only ill-formed if the deleted function was selected.

So if cppreference is correct and my program is ill-formed does this just mean it will not compile or is it unspecified or undefined behavior?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Your program is ill-formed. First, for each invocation of foo, we perform overload resolution. That will call:

foo(1);            // foo(int )
foo(3.0);          // foo<T>, T=double
foo(short(5));     // foo<T>, T=short
foo(float(7.0));   // foo<T>, T=float
foo(long(9));      // foo<T>, T=long

Four of those functions are explicitly deleted and, from [dcl.fct.def.delete]:

A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed.

It's not undefined or unspecified behavior. It should simply not compile.


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

...