Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template with reference template parameter

Tags:

c++

templates

There is this code:

#include <iostream>

template<const double& f>
void fun5(){
    std::cout << f << std::endl;
} 

int main() 
{ 
    const double dddd = 5.0;
    fun5<dddd>();
    return 0;
} 

Compiler error during compilation:

$ g++ klasa.cpp -o klasa
klasa.cpp: In function ‘int main()’:
klasa.cpp:11:10: error: ‘dddd’ cannot appear in a constant-expression
klasa.cpp:11:16: error: no matching function for call to ‘fun5()’
klasa.cpp:11:16: note: candidate is:
klasa.cpp:4:6: note: template<const double& f> void fun5()

Why placing 'dddd' as template parameter doesn't work and what should be done to make it work?

like image 875
scdmb Avatar asked Feb 22 '23 13:02

scdmb


1 Answers

References and pointers for template arguments must have external linkage (or internal linkage, for C++11, but static storage duration is required). So if you have to use dddd as a template argument, you need to move it to global scope and make it extern:

extern const double dddd = 5.0;
int main()
{
    fun5<dddd>();
    return 0;
}
like image 150
kennytm Avatar answered Mar 03 '23 04:03

kennytm