Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Template specialization with float as non type

Section 4.3 of C++ Templates states 'Not being able to use floating-point literals (and simple constant floating-point expressions) as template arguments has historical reasons.'

Similarly,

$14.1/7 states - "A non-type template-parameter shall not be declared to have floating point, class, or void type. [ Example:

template<double d> class X; // error
template<double* pd> class Y; // OK
template<double& rd> class Z; // OK"
  1. What is the historical reason that is being talked about in the book in the above quote?

  2. Looking at why Y and Z are valid but not X, is the whole challenge related to having non type template parameters of floating type got to do anything with pointers/references?

  3. Why template non type parameters can not be of class type?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It could be hard to pick the right template instantitiation, because of possible roundoff errors .

Consider the following:

template<float n> 
void f(n) {...}  //Version 1

template<0.3333> 
void f() { ...} // Version 2:Specialization for 0.3333 

f(1/3); -> Which version would be called?

Consider the following code:

template <float f> class foo { ... }; 
foo<1E6 + 1E-6> my_foo; 

" What should the compiler generate? The compiler has to know about the details of target floating-point architecture to be able to run instantiate the template. This is easy enough if the compiler is running on the target architecture, it can just do the calculation and find out the answer, but if you are cross-compiling, the compiler would have to be able to synthesise the floating point behaviour of every intended target architecture. And thankfully the Standards Committee decided that this would be unreasonable. "

Shamelessly copied from here.

Why template non type parameters can not be of class type

As per my understanding a non-type paramater cannot be of class type because there may be more than one implementation of a class. For example

template <typename T>   
class demo{...};

template <>    
class demo<int>{...};


template <typename T, demo d> //which demo?? demo<T> or demo<int>
class Example{...};

Local classes cannot be used as template parameters because they don't have external linkage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...